<?php
define('API_ERR_APP_KEY', 'You application Key is invalid');
define('API_ERR_API_CALL', 'Application cant make requested api call'); 


class API{
	
	private $_apiKeyList = array(
		'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //API_KEY API_SECRET
		);
	
	private $_request = array();
	private $_errors	= array();
	private $_reponse = array();
	
	function __construct($appID, $enc_req, $methodToCall = null){
		$appID 	 = 'APP001';
		
		
		#check if app key is valid 
		if( isset( $this->_apiKeyList[$appID]) ){
			#decode the app request
			$this->_request = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->_apiKeyList[$appID], base64_decode($enc_req), MCRYPT_MODE_ECB)), true);
			
			#call the function
			$controller = F::get()->Controller();
			
			#Check if function exists and if the function is public
			if( method_exists($this, $methodToCall ) && strpos($methodToCall, '_') !== 1){
				$this->_reponse =  $this->{$methodToCall}() ;
			}else{
				$this->_setError(API_ERR_API_CALL);
			}
		}else{
			$this->_setError(API_ERR_APP_KEY);
		}
		
		$this->_reponse['errors']    = (bool) $this->_errors;
		$this->_reponse['errorMsgs'] = $this->_errors;
	}
	
	
	//API_KEY
	
	
	public function _draw(){
		die(''.json_encode($this->_reponse));
	}
	public function _return(){
		return(''.json_encode($this->_reponse));
	}
	public function _returnArray(){
		return $this->_reponse;
	}
	
	/*============= System ( private ) Api Function =============*/
	/**
	* Set API error messages
	* @param $error 
	* @return mixed 
	*/
	public function _setError($error){
		$this->_errors[] = $error; 
	}
	
	/*============= Public Function =============*/
	
	public function login(){
		$users 	= F::get()->loader('Users');
		$userID = $users->login($this->_request['username'], $this->_request['password']);
		return array('userID'=>$userID);
	}
	
	# key, method, postdata
	public function callTableClassMethod(){  
		$decryptedArr = json_decode( F::get()->Crypt()->decrypt($this->_request['key']), true );
		$class  			= F::get()->loader($decryptedArr['tableName'], $decryptedArr['columnId'], true, $decryptedArr['columnName']);
		
		
		$out = array();
		$out['html']  			 = capture($class, $this->_request['method'], $this->_request['postdata']);
		$out['title'] 			 = $decryptedArr['classTitle'];
		
		$out['sesssion_template_message'] = $_SESSION['template']['message']; #return session messages 
		
		
		return $out;
	}
	
	
	#tableName , columnId, columnName, switch
	public function callTableClassKey(){
		$class  			= F::get()->loader($this->_request['tableName'], $this->_request['columnId'], false, $this->_request['columnName']);
		$out = array();
		$out['key'] = $class->getFormKey();
		return $out;
	}
	
	public function test(){
		return $_POST;
	}
	
	
}
?>
